var sqlite3 = require('sqlite3').verbose();

var formatObject = function (res) {
    let _data = {};
    for (const key in res) {
        if (res.hasOwnProperty(key)) {
            const _item = res[key];
            var index = key.indexOf('_');
            if (index != -1) {
                var _indexArray = key.split('_');
                var _$indexArray = [];
                for (let i = 0; i < _indexArray.length; i++) {
                    const element = _indexArray[i];
                    if (i != 0) {
                        _$indexArray.push(element[0].toUpperCase() + element.substr(1));
                    } else {
                        _$indexArray.push(element);
                    };
                };
                var _key = _$indexArray.join('');
                _data[_key] = _item;
            } else {
                _data[key] = _item;
            };
        }
    };
    return _data;
};
var formatArray = function (res) {
    var data = [];
    for (let i = 0; i < res.length; i++) {
        const element = res[i];
        var _data = formatObject(element);
        data.push(_data);
    };
    return data;
};

class _DB_ {
    constructor() {
        this.filePath = './test.db';
        this.db = new sqlite3.Database(this.filePath, function (err) { });
    }
    creat(sql) {
        return new Promise((resolve, rejected) => {
            this.db.run(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(res);
                };
            });
        });
    }
    update(sql) {
        return new Promise((resolve, rejected) => {
            this.db.run(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(res);
                };
            });
        });
    }
    find(sql) {
        return new Promise((resolve, rejected) => {
            this.db.all(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(formatArray(res));
                };
            });
        });
    }
    get(sql) {
        return new Promise((resolve, rejected) => {
            this.db.get(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(formatObject(res));
                };
            });
        });
    }
    delete(sql) {
        return new Promise((resolve, rejected) => {
            this.db.run(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(res);
                };
            });
        });
    }
}

module.exports = _DB_;

